package com.example.androidrssreader;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;

/**
 * Class extends ArrayAdapter<RssItem> that provides adapter for RSS ListView
 *  
 * @author gylka
 *
 */
public class RssListAdapter extends ArrayAdapter<RssItem> {
	
	private LayoutInflater inflater;
	private List<RssItem> items;
	private Context context;

	public RssListAdapter(Context context, int textViewResourceId, List<RssItem> objects) {
		super(context, textViewResourceId, objects);
		this.context = context;
		this.items = objects;
		this.inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
	}
	
	@Override
	public View getView (int position, View convertView, ViewGroup parent) {
		View view = convertView;
        if(convertView==null)
            view = inflater.inflate(R.layout.rss_list_item, parent, false);
        TextView txtRssTitle = (TextView)view.findViewById(R.id.txtRssTitle);
        txtRssTitle.setText(items.get(position).title);
        
        TextView txtRssDescription = (TextView) view.findViewById(R.id.txtRssDescription);
       	txtRssDescription.setText(items.get(position).description);
        TextView txtRssPubDate = (TextView) view.findViewById(R.id.txtRssPubDate);
       	txtRssPubDate.setText(items.get(position).pubDate);
        
       	Button btnExpand = (Button) view.findViewById(R.id.btnExpand);

       	// Setting OnClinkListener so Button "more" will show RssDetailActivity and send RSS data to it
       	final int pos = position;
       	btnExpand.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				Intent intent = new Intent(context, RssDetailActivity.class);
				intent.putExtra(MainActivity.PACKAGE_NAME+".RssItem.title", items.get(pos).title);
				intent.putExtra(MainActivity.PACKAGE_NAME+".RssItem.pubdate", items.get(pos).pubDate);
				intent.putExtra(MainActivity.PACKAGE_NAME+".RssItem.fulltext", items.get(pos).fullText);
				intent.putExtra(MainActivity.PACKAGE_NAME+".RssItem.link", items.get(pos).link);
				intent.putExtra(MainActivity.PACKAGE_NAME+".RssItem.pdalink", items.get(pos).pdaLink);
				context.startActivity(intent);
			}
		});
       	
        return view;
	}
	
}
